package com.wulis.generator.utils;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author WuliBao
 */
@Slf4j
public class CommonUtil {

    /**
     * 获取信息作者
     */
    public static String getAuthor() {
        // 默认hostName
        String hostName = "Unknown";
        try {
            // 获取本机计算机名称
            String author = InetAddress.getLocalHost().getHostName();
            // 极端情况获取的网卡计算机名称为：Unknown
            if (!hostName.equalsIgnoreCase(author)) {
                return author;
            }
        } catch (UnknownHostException e) {
            log.error(e.getMessage());
        }
        return "admin";
    }

    /**
     * 获取父类的字段
     *
     * @return List
     */
    public static List<String> superEntityColumnsContainId(Class<?> clazz) {
        // 获取对象 属性注释 准备集合接收 字段注释
        List<String> fieldList = new ArrayList<>();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            boolean annotation = field.isAnnotationPresent(TableId.class);
            if (annotation) {
                String value = field.getAnnotation(TableId.class).value();
                fieldList.add(value);
            }
            annotation = field.isAnnotationPresent(TableField.class);
            if (annotation) {
                String value = field.getAnnotation(TableField.class).value();
                fieldList.add(value);
            }
        }
        return fieldList;
    }

    /**
     * 获取父类的字段
     *
     * @return List
     */
    public static List<String> superEntityColumns(Class<?> clazz) {
        // 获取对象 属性注释 准备集合接收 字段注释
        List<String> fieldList = new ArrayList<>();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            boolean annotation = field.isAnnotationPresent(TableField.class);
            if (annotation) {
                String value = field.getAnnotation(TableField.class).value();
                fieldList.add(value);
            }
        }
        return fieldList;
    }
}
